<template>
  <view :class="{ turntable: true, 'turntable-bg': type !== -1 && !winAward }">
    <view class="gainCount" v-if="gainCount" v-show="!showInModal">您已获得{{ gainCount }}次抽奖机会</view>
    <view
      class="wrapper"
      :style="{ backgroundImage: `url(${imageUrl}${lotteryInfo.turntablePicUrl})`, transform: `scale(${scale})` }"
      v-show="!showInModal"
    >
      <view class="panel" :style="{ transform }" @transitionend="endTurn">
        <view
          class="sector"
          v-for="(item, index) of lotteryInfo.lotteryPrizeRespList"
          :key="item.id"
          :style="{ transform: `rotate(${getAwardDeg(index)}deg)` }"
        >
          <view
            class="sector-inner"
            :style="{
              transform: `translateX(-100%) rotate(${rewardRotateDeg}deg)`,
              paddingTop: `${offset}rpx`,
              paddingLeft: `${(90 / (rewardRotateDeg * 2) / 3) * 100}%`
            }"
          >
            <view
              :style="{ transform: `rotate(${360 - rewardRotateDeg / 2}deg)`, marginRight: `-${offset / 2}rpx`, paddingLeft: `${offset / 2}rpx` }"
            >
              <view class="span">{{ item.title }}</view>
              <x-image :src="item.picUrl" class="image" width="60rpx" height="60rpx" mode="aspectFit" />
            </view>
          </view>
        </view>
      </view>
      <x-image :src="lotteryInfo.turntablePointPicUrl" v-if="lotteryInfo.turntablePointPicUrl" class="pointer" @tap="drawLottery" />
      <view class="draw-count">剩余抽奖{{ lotteryInfo.myDrawCount || 0 }}次</view>
    </view>

    <van-popup
      v-if="winAward"
      :show="winAward"
      @close="handleClose"
      :custom-style="`background: transparent; display: flex; flex-direction: column; width: ${winAward ? '680rpx' : '0'}`"
      :overlay="!showInModal"
    >
      <view class="ad-modal-img" :style="{ backgroundImage: lotteryResult.isWin ? `url(${imageUrl}${lotteryInfo.windowBgPicUrl})` : '' }">
        <template v-if="lotteryResult.isWin">
          <view class="award">恭喜您获得{{ lotteryResult.prizeTitle }}</view>
          <x-image :src="lotteryResult.picUrl" class="picUrl" mode="aspectFit" width="440rpx" height="440rpx" />
        </template>
        <x-image src="https://staticcdn.youliao.com/static/image/www_pc/activity/festival/icon-noAward.png" width="564rpx" height="541rpx" v-else />
      </view>
      <van-icon name="close" @tap="handleClose" color="#fff" size="32px" style="margin-top: 20rpx" />
    </van-popup>
  </view>
</template>

<script>
import marketService from "@/api/market";

export default {
  name: "turntable",
  props: {
    scale: {
      type: Number,
      default: 1
    },
    type: {
      type: Number,
      default: -1
    }
  },
  data() {
    return {
      onRotation: false, // 记录当前是否正在旋转，如果正在旋转，就不能继续点击了
      transform: "rotateZ(0deg)",
      currentDeg: 0,
      offsetDeg: 0,
      lotteryInfo: {
        turntablePicUrl: "",
        turntablePointPicUrl: "",
        lotteryPrizeRespList: [],
        myDrawCount: 0
      },
      lotteryResult: {},
      winAward: false
    };
  },
  created() {
    this.getLotteryInfo();
  },
  methods: {
    async getLotteryInfo() {
      const { status, data, msg } = await marketService.getLotteryInfo({ id: 0 });
      if (status !== 1) {
        uni.showToast({
          title: msg,
          icon: "none"
        });
        return;
      }
      this.lotteryInfo = data;
    },

    handleClose() {
      this.winAward = false;
      !this.lotteryInfo.myDrawCount && this.$emit("show", false);
    },

    getAwardDeg(index) {
      return index * this.rewardRotateDeg - this.rewardRotateDeg / 2;
    },

    async drawLottery() {
      if (this.onRotation || !this.lotteryInfo.lotteryPrizeRespList.length || this.disabled) return;

      const token = uni.getStorageSync("yl-token");
      token && (this.disabled = true);
      const { status, data, msg } = await marketService.drawLottery({ id: 0 }).finally(() => {
        this.disabled = false;
      });
      if (status !== 1) {
        uni.showToast({
          title: msg,
          icon: "none"
        });
        return;
      }

      this.lotteryResult = data;
      this.lotteryResult.selectAwardIndex = this.lotteryInfo.lotteryPrizeRespList.findIndex((item) => item.id === this.lotteryResult.prizeId);
      this.lotteryInfo.myDrawCount = data.myDrawCount;
      this.startTurn();
    },

    startTurn() {
      const getRewardDeg = () => {
        const offsetDeg = this.getAwardDeg(this.lotteryResult.selectAwardIndex) + this.rewardRotateDeg / 2;

        // 转三圈到四圈
        const rotateDeg = 360 * 3 + this.offsetDeg - offsetDeg;
        this.offsetDeg = offsetDeg;
        return rotateDeg;
      };

      this.onRotation = true;
      this.currentDeg += getRewardDeg();
      this.transform = `rotateZ(${this.currentDeg}deg)`;
    },

    endTurn() {
      this.onRotation = false;
      this.winAward = true;
      this.$emit("finish");
    }
  },
  computed: {
    imageUrl() {
      return this.config_url.imageUrl;
    },
    rewardRotateDeg() {
      return 360 / this.lotteryInfo.lotteryPrizeRespList.length;
    },
    offset() {
      return 26 - (this.lotteryInfo.lotteryPrizeRespList.length - 6);
    },
    gainCount() {
      if (!this.lotteryInfo.lotteryTaskRespList) return 0;

      const { lotteryTaskRespList = [], isShow } = this.lotteryInfo;
      const gainCountObj = this.type && lotteryTaskRespList.find((item) => item.type === this.type && item.isFinish);
      const gainCount = gainCountObj && gainCountObj.gainCount;
      lotteryTaskRespList.length && this.$emit("show", this.lotteryInfo.myDrawCount && gainCount && isShow);
      return gainCount || 0;
    },
    showInModal() {
      return this.winAward && this.type !== -1;
    }
  },
  watch: {
    winAward(winAward) {
      this.$emit("update:hideTurntable", winAward);
    }
  }
};
</script>

<style lang="scss" scoped>
.ad-modal-img {
  cursor: pointer;
  position: relative;
  width: 100%;
  height: 638rpx;
  background-size: 100%;
  background-position: center;
  background-repeat: no-repeat;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  z-index: 100;

  .award {
    color: #ff534e;
    font-size: 28rpx;
    text-align: center;
  }

  .picUrl {
    width: 440rpx;
    margin: auto;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .icon {
    color: rgba(255, 255, 255, 0.8);
    position: absolute;
    left: 0;
    right: 0;
    bottom: -60rpx;
    font-size: 32rpx;
    cursor: pointer;
  }
}

.turntable {
  width: 720rpx;
  margin: auto;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;

  $turnWidth: 616rpx;
  $color: #f03526;

  .gainCount {
    color: $color;
    font-size: 36rpx;
    font-weight: 600;
    text-align: center;
    margin-bottom: -20rpx;
  }

  .wrapper {
    position: relative;
    width: $turnWidth;
    height: 716rpx;
    background-size: cover;
    margin: auto;

    $panelWidth: 450rpx;
    $offset: ($turnWidth - $panelWidth) / 2;

    .panel {
      position: absolute;
      width: $panelWidth;
      height: $panelWidth;
      border-radius: 50%;
      top: $offset;
      left: $offset;
      transition: transform 3s cubic-bezier(0.2, 0.93, 0.43, 1);
      overflow: hidden;

      .sector {
        position: absolute;
        left: 50%;
        width: 50%;
        height: 100%;
        font-size: 14rpx;
        border-radius: 0rpx 100rpx 100rpx 0;
        overflow: hidden;
        transform-origin: left center;

        &:nth-child(2n + 1) .sector-inner {
          background: #ffe195;
        }
        &:nth-child(2n) .sector-inner {
          background: #ffffff;
        }
      }

      .sector-inner {
        text-align: center;
        height: 100%;
        transform-origin: right center;
        border-radius: 100rpx 0 0 100rpx;

        .span {
          display: block;
          transform-origin: center;
          color: $color;
          font-size: 24rpx;
          text-align: center;
          margin-bottom: 20rpx;
        }
      }
    }

    .pointer {
      $pointerWidth: 180rpx;
      position: absolute;
      left: ($turnWidth -$pointerWidth) / 2;
      top: ($turnWidth -$pointerWidth) / 2;
      z-index: 10;

      ::v-deep image {
        width: $pointerWidth;
        height: $pointerWidth;
      }
    }

    .draw-count {
      position: absolute;
      width: 100%;
      bottom: 26rpx;
      font-size: 28rpx;
      font-weight: 400;
      color: #fff;
      text-align: center;
    }
  }
}

.turntable-bg {
  background-image: url("https://staticcdn.youliao.com/static/image/www_pc/activity/festival/turntable-bg.png");
  background-repeat: no-repeat;
  background-size: cover;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 20rpx;
}
</style>
